<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>考试详情</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <link href="../../../css/mui.min.css" rel="stylesheet" />
    <link href="../css/common.css" rel="stylesheet" />
    <style>
      .mui-slider-group{
        height:calc(100vh - 125px);
      }
      .mui-control-content {
        background-color: white;
        min-height:calc(100vh - 125px);
        /* min-height: 100vh; */
      }
      .border-bottom{
        border-bottom:1px solid #F2F2F2;
      }
      .mui-input-group:before,.mui-input-group:after{
        height: 0px;
      }
      .mui-input-group .mui-input-row:after{
        height: 0px;
      }
      .mui-checkbox input[type=checkbox]:before, .mui-radio input[type=radio]:before{
        font-size: 24px;
      }
      .mui-checkbox input[type=checkbox], .mui-radio input[type=radio]{
        top: 5px;
      }
      .mui-radio input[type=radio]:checked:before {content: '\e442';}
      /* 单选框错误的时候 */
      /* .mui-radio input[type=radio]:checked:before {content: '\e434';} */
      .mui-checkbox input[type=checkbox]:before {
        content: '\e413';
      }		
      .mui-checkbox input[type=checkbox]:checked:before {
        content: '\e443';
      }	
      .mui-checkbox input[type=checkbox]:before{
        font-size: 22px;
      }
      .mui-checkbox input[type=checkbox]{
        top: 6px;
      }
       .button button{
         width: 100%;
         text-align: center;
         line-height: 1.6rem;
       } 
        .button button.prev{
          color: #275EB1;
          border:1px solid #275EB1;
        } 
        .button button.next{
          color: #ffff !important;
          border:1px solid #275EB1;
          background-color: #275EB1;
        }  
       .container{
         height: 100vh;
       }
       .answerCard {
       	position: fixed;
       	bottom: 6.4rem;
       	right: 1.5rem;
        z-index: 99;
       }
       
       .answerCard img {
       	width: 4.5rem;
       	height: 4.5rem;
       }
       .examPopUp{
         width: 100%;
         left: 0;
         bottom: 0;
         right: 0;
         height:calc(100vh - 200px);
         background-color: #fff;
         border-radius: 7px 7px 0 0;
       }
       .not {
       	width: 15px;
       	height: 15px;
       	border: 1px solid #bfbfbf;
       	vertical-align: middle;
       }
       .already {
       	width: 15px;
       	height: 15px;
       	background: rgba(19, 173, 243, .1);
       	border: 1px solid rgba(0, 160, 233);
       	vertical-align: middle;
       }
       .cardContent{
         height:calc(100vh - 200px - 116px - 50px);
         position: relative;
       }
       .grid {
       	display: flex;
       	flex-wrap: wrap;
       }
       .grid.col-8>div {
       	margin: 10px 0;
       	/* padding-bottom: calc((100% - 60upx)/7); */
       	/* height: 0; */
       	width: calc(100%/8);
       	text-align: center;
       	line-height: auto;
       }
       
       .not-lg {
       	width: 30px;
       	height: 30px;
       	line-height: 30px;
       	border: 1px solid #bfbfbf;
       	vertical-align: middle;
       }
       
       .already-lg {
       	width: 30px;
       	height: 30px;
       	line-height: 30px;
       	color: #1782E5;
       	background: rgba(19, 173, 243, .1);
       	border: 1px solid rgba(0, 160, 233);
       	vertical-align: middle;
       }
       .cu-bar {
       	display: flex;
       	position: relative;
       	align-items: center;
       	min-height: 3rem;
       	justify-content: space-between;
       }
       .cu-bar div {
       	height: 3rem;
       	line-height: 3rem;
        text-align: center;
       }
       .solid-top{
         border-top: 1px solid #DCDCDC;
       }
       .button div{
         padding:0.8rem 0;
       }
	   .mui-toast-container {
	       bottom: 50% !important;/*离布局底部的距离*/
	   }
	   * { touch-action: pan-y; }
    </style>
  </head>
  <body>
    <div class="container bg-white" id="container" v-cloak>
      <header class="mui-bar mui-bar-nav">
        <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
        <h1 class="mui-title"><span>{{h}}</span>：<span>{{i}}</span>：<span>{{s}}</span></h1>
      </header>
      <div id="" class="mui-content bg-white">
        <div class="answerCard" @click="showCard()">
          <img src="../img/answerCard.png">
        </div>
        <div id="slider" class="mui-slider">
          <div class="mui-slider-group">
            <div class="mui-slider-item mui-control-content" v-for="(item,index) in examList" :key="index">
              <div class="mui-scroll-wrapper">
                <div class="mui-scroll">
                  <div class="text-blue padding text-df border-bottom">
                    <span v-if="item.type==1">单选题</span>
                    <span v-if="item.type==2">多选题</span>
                    <span v-if="item.type==3">判断题</span>
                  </div>
                  <div class="examContent padding">
                    <div class="text-black title flex align-start">
                      <div class="text-orange padding-right-xs">第{{index+1}}/{{examList.length}}题</div>
                      <div class="flex-sub" style="width: 356px;" v-html="item.subject"></div>
                    </div>
                    <div class="padding-top">
                      <form class="mui-input-group" v-if="item.type==1">
                        <div class="mui-input-row mui-radio mui-left" v-for="opt in item.userQuestionOptList">
                          <label v-html="opt.optDesc"></label>
                          <input name="a" type="radio" :value="opt.optIndex" v-model="item.userOpt">
                        </div>
                      </form>
                      <form class="mui-input-group" v-if="item.type==2">
                        <div class="mui-input-row mui-checkbox mui-left" v-for="opt in item.userQuestionOptList">
                          <label v-html="opt.optDesc"></label>
                          <input :name="opt.optIndex" type="checkbox" :value="opt.optIndex" v-model="item.userOpt">
                        </div>
                      </form>
                      <form class="mui-input-group" v-if="item.type==3">
                        <div class="mui-input-row mui-radio mui-left">
                          <label>正确</label>
                          <input name="a" type="radio" value="T" v-model="item.userOpt">
                        </div>
                        <div class="mui-input-row mui-radio mui-left">
                          <label>错误</label>
                          <input name="a" type="radio" value="F" v-model="item.userOpt">
                        </div>
                      </form>
                    </div>
                  </div>
                 
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="button flex padding-lr">
          <div class="flex-sub margin-right">
            <button class="prev" @click="prev()">上一题</button>
          </div>
          <div class="flex-sub">
            <button class="next" @click="submit()" style="color: #fff;" v-if="examIndex===(examList.length-1)">提交</button>
            <button class="next" @click="next()" style="color: #fff;" v-else>下一题</button>
          </div>
        </div>
      </div>
      <!-- <div id="topPopover" class="popUp mui-popover mui-popover-add" data-type="" style="min-height: 20vw; overflow: hidden;">
        <div class="padding flex justify-end">
          <div class="mui-icon mui-icon-closeempty" style="font-size: 30px;"> 
          </div>
        </div>
      	<div class="padding text-center">
          <div>确定提交吗</div>
        </div>
      	<div class="flex justify-between button solid-top margin-top-lg">
      		<div class="flex-sub text-center solid-top right">
      			取消
      		</div>
      		<div class="flex-sub text-center text-white bg-blue">
      			确定
      		</div>
      	</div>
      </div> -->
      <div class="examPopUp mui-popover mui-popover-add" id="popUp">
        <div class="flex bg-white justify-end align-center border-bottom">
          <div class="flex-sub text-center text-df padding-tb">答题卡</div>
          <div class="action" @click="hideCard">
            <span class="mui-icon mui-icon-closeempty text-grey" style="font-size: 34px;"></span>
          </div>
        </div>
        <div class="flex justify-between text-sm padding-lr margin-top-sm">
          <div class="text-grey">
            <span>已答题：{{examList,'already'|num}}</span>
            <span class="margin-left">剩余：{{examList,'not'|num}}</span>
          </div>
          <div class="flex align-center">
            <div class="not margin-lr-sm"></div>
            <div class="">未答</div>
            <div class="already margin-lr-sm"></div> 已答
          </div>


        </div>
        <div class="cardContent margin">
          <div class="mui-scroll-wrapper">
            <div class="mui-scroll">
              <!--这里放置真实显示的DOM内容-->
              <div class="grid col-8">
                <div v-for="(item,index) in examList">
                  <div :class="item.userOpt.length===0?'not-lg':'already-lg'" @click="AppointedSubject(index)">{{index+1}}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="cu-bar bg-white text-df solid-top">
          <div class="flex-sub text-red" @click="hideCard">进入答题</div>
          <div class="flex-sub bg-blue text-white" @click="submit">交卷</div>
        </div>
      </div>
    </div>
    </div>
    <script src="../../../js/mui.min.js"></script>
    <script src="../../../js/jquery-3.2.1.min.js"></script>
    <script src="../js/mkeyplus.base.js"></script>
    <script type="text/javascript" src="../../../js/vue.js"></script>
    <script src="../formal/js/api.js"></script>
    <script type="text/javascript">
      var exam = null;
      var htapi = new HTGlobal();
      var user = JSON.parse(localStorage.getItem('outUser')); //当前用户信息
      var cv = null,
        id = null;
        // mui('#topPopover').popover('show')
		
		
	var slider = undefined
      mui.plusReady(function() {
        cv = plus.webview.currentWebview();
        console.log(cv.form);
        id = cv.pageId ? cv.pageId : '';
        plus.nativeUI.showWaiting('加载中');
        exam.getData(id)
         
      })
      exam = new Vue({
        el: '#container',
        data: {
          timer: null,
          d: '00',
          h: '00',
          i: '00',
          s: '00',
          examIndex: 0, //跳转索引
          answerIndex: 0, //题目索引
          examList: [],//试题列表
          seconds: 0,//倒计时
          letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'],
          detail:{},//整体试题详情
          Tips:'确定提交试卷吗？'//提示语
        },
        created: function() {

        },
        beforeDestroy() {
        	clearInterval(this.timer)
        },
        filters: {
          num(val, type) {
            var i = 0;
            for (var j = 0; j < val.length; j++) {
            	if (val[j].userOpt.length === 0) {
            		i += 1
            	}
            }
            if (type == 'not') {
              return i;
            } else {
              return val.length - i;
            }
          }
        },
        onShow() {
          console.log('页面显示')
        },
        methods: {
          // 获取倒计时
          getCountdown(id) { //获取详情
            var that = this;
            mui.baseWApp.httpRequst("/outsider/app/userPaperResult/getCountdown/" + id, {}, function(data) {
              if (data.code == '0') {
                console.log('倒计时' + JSON.stringify(data));
                that.seconds = data.data;
				if(!that.seconds){
					//还原返回键
					mui.back = old_back
				}
                that.startData();
              }
            }, function() {
              plus.nativeUI.closeWaiting();
              console.log("获取数据失败");
            })
          },
          //考试详情
          getData(id) {
            var that = this;
            htapi.fetch({
              examPaperId: id,
              userId: user.id,
			  enterpriseProjectId:user.enterpriseProjectId
            }, function(data) {
              if (data.code == '0') {
                that.getCountdown(data.data.id)
                data.data.userQuestionList.forEach(function(item) {
                  
                    if(item.type==2){
                      if(item.userOpt){
                        item.userOpt=item.userOpt.split("、") 
                      }else{
                        item.userOpt=[]
                      }
                       
                    }
                    item.userQuestionOptList.forEach(function(opt) {
                    	var index = Number(opt.optIndex) - 1
                    	opt.optIndex = that.letters[index]
						if(/^(\s?<.+?>)/ig.test(opt.optDesc)){
							opt.optDesc = opt.optDesc.replace(/^(\s?<.+?>)/ig,"$1"+opt.optIndex+": ")
						}else{
							opt.optDesc = opt.optIndex+": "+opt.optDesc
						}
						
                      opt.optDesc = opt.optDesc.replace(/\<img/gi,
                          '<img style="max-width: 60%;margin:15upx 0;"');
					  opt.optDesc = opt.optDesc.replace(/src=['"]([^'"]+)['"]/ig,"src='($1)?userId="+user.id+"'")
                    })
					item.subject = item.subject.replace(/\<img/gi,
					  '<img style="max-width:100%;"');
					item.subject = item.subject.replace(/src=['"]([^'"]+)['"]/ig,"src='($1)?userId="+user.id+"'")
                })
                that.detail=data.data;
                that.examList = data.data.userQuestionList;
                
                that.$nextTick(function(){//dom渲染完初始化
                  slider = mui(".mui-slider").slider({deceleration:0.0002});
                });
                
              }
              // console.log(JSON.stringify(data))
            }, '加载中', 'examDeatil')
          },
          // 显示答题卡
          showCard() {
            mui('#popUp').popover('show')
          },
          // 隐藏答题卡
          hideCard() {
            mui('#popUp').popover('hide')
          },
          //获取倒计时
          secondsFormat(s) {
            var that = this
            that.reset = !that.reset;
            var day = Math.floor(s / (24 * 3600)); // Math.floor()向下取整 
            var hour = Math.floor((s - day * 24 * 3600) / 3600);
            var minute = Math.floor((s - day * 24 * 3600 - hour * 3600) / 60);
            var second = s - day * 24 * 3600 - hour * 3600 - minute * 60;
            that.day = day
            that.hour = hour
            that.minute = Number(minute < 10 ? '0' + minute : minute)
            that.second = Number(second < 10 ? '0' + second : second)
            that.$set(that, 'day', day);
            that.$set(that, 'hour', hour);
            that.$set(that, 'second', Number(second < 10 ? '0' + second : second));
            that.$set(that, 'minute', Number(minute < 10 ? '0' + minute : minute));
            that.$forceUpdate()
          },
          toSeconds(day, hours, minutes, seconds) {
            return day * 60 * 60 * 24 + hours * 60 * 60 + minutes * 60 + seconds
          },
          timeUp() {
            clearInterval(this.timer)
            console.log('倒计时结束')
            // this.answer(this.answerIndex,3);//倒计时结束提交试卷
            this.timeEnd()
          },
          countDown() {
            var seconds = this.seconds
            var [day, hour, minute, second] = [0, 0, 0, 0]
            if (seconds > 0) {
              day = Math.floor(seconds / (60 * 60 * 24))
              hour = Math.floor(seconds / (60 * 60)) - (day * 24)
              minute = Math.floor(seconds / 60) - (day * 24 * 60) - (hour * 60)
              second = Math.floor(seconds) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
            } else {
              this.timeUp()
            }
            if (day < 10) {
              day = '0' + day
            }
            if (hour < 10) {
              hour = '0' + hour
            }
            if (minute < 10) {
              minute = '0' + minute
            }
            if (second < 10) {
              second = '0' + second
            }
            this.d = day
            this.h = hour
            this.i = minute
            this.s = second
          },
          startData() {
            if (this.seconds <= 0) {
              this.d = '00'
              this.h = '00'
              this.i = '00'
              this.s = '00'
              return
            }
            this.countDown()
			var _this = this
            this.timer = setInterval(function(){
              _this.seconds--
              if (_this.seconds < 0) {
                _this.timeUp()
                return
              }
              _this.countDown()
            }, 1000)
          },
          prev:throttle(function(e) { //上一题
            if (this.examIndex == 0) {
               mui.toast("这已经是第一题了")
              return
            }
            if (this.examIndex != 0) {
              this.examIndex -= 1;
            }
            //var slider = mui('.mui-slider').slider({deceleration:0.0002}); //跳转到相对应的滑块
            slider.gotoItem(this.examIndex);
          },'500'),
          next:throttle(function(e) { //下一题
			console.log(JSON.stringify(this.examList));
            this.examIndex += 1;
            //var slider = mui('.mui-slider').slider({deceleration:0.0002}); //跳转到相对应的滑块
            slider.gotoItem(this.examIndex);
          },'500'),
          AppointedSubject(index) { //题卡指定
            this.examIndex = index;
            this.hideCard()
            //var slider = mui('.mui-slider').slider({deceleration:0.0002}); //跳转到相对应的滑块
            slider.gotoItem(this.examIndex);
          },
          answer(index,type){//type==2代表点击了提交 type==3代表时间结束强制提交试卷
            var that=this;
            var userOpt=that.examList[index].userOpt
            if(that.examList[index].type==2){
              userOpt= userOpt.sort().join('、');
            }
            console.log(JSON.stringify(that.examList[index]))
           var data={
             id: that.examList[index].id,
             userOpt: userOpt,
             userId: user.id,
             userPaperId: that.detail.id,
             questId: that.examList[index].questId,
			 enterpriseProjectId:user.enterpriseProjectId
           }
		   //console.log(JSON.stringify(user));return;
           htapi.fetch(data,function(data){
             console.log('提交成功'+JSON.stringify(data))
             if(data.code=='0'){
               
               if(type==2){
                 that.handPapers()
               } else if (type == 3){
                that.timeEnd()
              }
             }else{
               mui.toast(data.msg)
             }
             
           },false,'answer','post')
          },
          handPapers(){//提交试卷
          var that=this;
            var btnArray = ['取消', '确定'];
            mui.confirm(that.Tips, '提示', btnArray, function(e) {
              if (e.index == 1) { 
                that.submitPapers()
              }
            })
          },
          submitPapers(){//交卷
            var that=this;
            plus.nativeUI.showWaiting('提交中...');
            var data={
              id: that.detail.id,
              userId: user.id,
            }
            htapi.fetch(data,function(data){
              if(data.code=='0'){
                console.log('提交成功'+JSON.stringify(data));
                var page=plus.webview.currentWebview().opener()
                mui.fire(page, 'examRefresh');
                mui.openWindow({
                  url: './examResult.html',
                  id: './examResult.html',
                  extras: {
                    data: JSON.stringify(data.data)
                  }
                });
              }
             plus.nativeUI.closeWaiting() 
            },false,'submitPaper','post')
          },
          timeEnd(){//倒计时结束提交试卷
            var that=this;
            mui.alert('请提交试卷', '提示', function() {
              that.submitPapers()
            });
          },
          
          submit:throttle(function(e){//点击提交先提交当前题
            
            var num = this.$options.filters['num'](this.examList,'not');
            console.log(num)
            if(num>0){
               this.Tips="您还有题未答完，确定提交吗？"  
            }else{
              this.Tips="确定提交试卷吗？"
            }
            this.answer(this.answerIndex,2)
            
          },'500')
        }
      })
      mui.init({
        swipeBack: false
      });
      mui('.mui-scroll-wrapper').scroll({
        indicators: false, //是否显示滚动条
        scrollY: true, //是否竖向滚动
      });
      /**
       * 监听滑动事件
       */
      document.getElementById('slider').addEventListener('slide', function(e) {
        console.log(e)
        console.log(e.detail.slideNumber)
        exam.answer(exam.answerIndex)//提交上一题
        exam.examIndex = e.detail.slideNumber
        exam.answerIndex = exam.examIndex;
      },{ passive: false })
	  
	  document.getElementById('slider').addEventListener('touchend',function(e){
	  		  if(!slider.moved)
	  		  slider.gotoItem(exam.examIndex);
	  })
	  
	  
      var old_back = mui.back;
      mui.back = function(){  
        mui.toast('正在考试中') 
      }	
      function throttle(fun, delay) {//节流
        var last, deferTimer;
        return function(args) {
          var that = this;
          var _args = arguments;
          var now = + new Date();
          if (last && now < last + delay) {
            clearTimeout(deferTimer);
            deferTimer = setTimeout(function() {
              last = now;
              fun.apply(that, _args);
            }, delay)
          } else {
            last = now;
            fun.apply(that, _args);
          }
        }
      }
    </script>
  </body>
</html>
